package com.zchat.android;

import org.jivesoftware.smack.packet.Presence;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zchat.android.app.BaseActivity;
import com.zchat.android.app.LauncherApplication;
import com.zchat.android.preferences.Preferences;
import com.zchat.android.receivers.LoggedInOutBroadcastReceiver;
import com.zchat.api.log.Logger;

/**
 * 
 * @author Oliverzhu
 *	2012/6/26
 */
public class LoginActivity extends BaseActivity {
	private static final String TAG = "LoginActivity";
	private EditText mEmailEditText;
    private EditText mPasswordEditText;
    
    private Button login;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.login);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initComponents() {
		mEmailEditText = 
				(EditText) findViewById(R.id.username);
		
		mPasswordEditText = 
				(EditText) findViewById(R.id.userpassword);
		
		login = (Button) findViewById(R.id.login);
		
		
	}

	@Override
	protected void initDatas() {

	}

	@Override
	protected void setComponentListeners() {

        login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new LoginTask().execute();
			}
		});
        
        login.setEnabled(false);
        TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            	login.setEnabled(phoneNumberEditTextFieldIsValid()
                        && passwordEditTextFieldIsValid());
            }

            private boolean phoneNumberEditTextFieldIsValid() {
                // This can be either a phone number or username so we don't
                // care too much about the
                // format.
                return !TextUtils.isEmpty(mEmailEditText.getText());
            }

            private boolean passwordEditTextFieldIsValid() {
                return !TextUtils.isEmpty(mPasswordEditText.getText());
            }
        };

        mEmailEditText.addTextChangedListener(fieldValidatorTextWatcher);
        mPasswordEditText.addTextChangedListener(fieldValidatorTextWatcher);
	}
	
	 private class LoginTask extends AsyncTask<Void, Void, Boolean> {
	        private static final String TAG = "LoginTask";
	        @Override
	        protected void onPreExecute() {
	            if (DEBUG) Logger.debug(TAG+"-onPreExecute()");
	            uiHandler.sendEmptyMessage(SHOWPROGRESSDIALOG);
	        }

	        @Override
	        protected Boolean doInBackground(Void... params) {
	            if (DEBUG) Logger.debug(TAG+"-doInBackground()");
	                String email = "coolis_me";
	                		//mEmailEditText.getText().toString();
	                String password = "jwen870629";
	                //mPasswordEditText.getText().toString();

	                boolean loggedIn = zchat.isAuthenticated(email, password);

	                // Make sure prefs make a round trip.
	                if(loggedIn)
	                {
	                	Preferences.storeUserNameAndPassword(mPrefs, email, password);
	                }
	                return loggedIn;
	        }

	        @Override
	        protected void onPostExecute(Boolean loggedIn) {
	            if (DEBUG) Logger.debug(TAG+"-onPostExecute()");

	            if (loggedIn) {
	                sendBroadcast(new Intent(LoggedInOutBroadcastReceiver.INTENT_ACTION_LOGGED_IN));
	                Toast.makeText(LoginActivity.this, getString(R.string.login_welcome_toast),
	                        Toast.LENGTH_LONG).show();
	                LauncherApplication launcherApplication = (LauncherApplication)getApplication();

	                // Launch the service to update any widgets, etc.
	                launcherApplication.requestStartService();
	                
	             // 登陆成功后，通知服务器用户处于在线状态
	        		Presence presence = new Presence(Presence.Type.available);
	        		zchat.getXMPPConnection().sendPacket(presence);

	                // Launch the main activity to let the user do anything.
	                Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
	                startActivity(intent);

	                HelpActivity helpActivity = 
	                		(HelpActivity) zchat.getCache().get("HelpActivity");
	                if(helpActivity != null)
	                {
	                	helpActivity.finish();
	                }
	                // Be done with the activity.
	                finish();

	            } else {
	                Toast.makeText(context, getString(R.string.loginError), Toast.LENGTH_SHORT).show();
	            }
	            uiHandler.sendEmptyMessage(CLOSEPROGRESSDIALOG);
	        }
	        
	        @Override
	        protected void onCancelled() {
	            uiHandler.sendEmptyMessage(CLOSEPROGRESSDIALOG);
	        }
	    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();
		default:
			break;
		}
		return true;
	}
	
	@Override
	public String toString() {
		return TAG;
	}

}
